package com.example.yyjc.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.yyjc.domain.selectionanalyze.CountrySecondCatCase;
import com.example.yyjc.domain.selectionanalyze.SecondCatGoodsTopTen;
import com.example.yyjc.domain.selectionanalyze.SecondCatShopTopTen;
import com.example.yyjc.service.SelectionService;
import com.example.yyjc.util.ResultBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @ClassName SelectionController
 * @Description TODO   选品分析
 * @Author lvyongwei
 * @Date 2020-11-30 17:26
 **/
@RestController
@CrossOrigin
@RequestMapping("/selection")
public class SelectionController {

    @Autowired
    private SelectionService selectionService;

    @Autowired
    private CountryController countryController;

    Logger logger = LoggerFactory.getLogger(SelectionController.class);

    /**
     * 获取某个国家二级类目行业规模趋势   选品分析4-1
     * @param data
     * @return
     */
    @PostMapping("/getSecondCatScale")
    public ResultBean getSecondCatScale(@RequestBody String data){
        /**
         * 解析参数
         */
        JSONObject jsonObject = JSONObject.parseObject(data);
        String countryName = jsonObject.getString("countryName");
        Integer firstCatId = jsonObject.getInteger("firstCatId");
        String beginTime = jsonObject.getString("beginTime");
        String endTime = jsonObject.getString("endTime");
        return ResultBean.success(selectionService.getSecondCatScale(countryName,firstCatId,beginTime,endTime));
    }

    /**
     * 获取某个国家二级类目行业规模占比    选品分析4-2
     * @param data
     * @return
     */
    @PostMapping("/getSecondCatScaleScale")
    public ResultBean getSecondCatScaleScale(@RequestBody String data){
        /**
         * 解析参数
         */
        JSONObject jsonObject = JSONObject.parseObject(data);
        String countryName = jsonObject.getString("countryName");
        Integer firstCatId = jsonObject.getInteger("firstCatId");
        String beginTime = jsonObject.getString("beginTime");
        String endTime = jsonObject.getString("endTime");
        List<CountrySecondCatCase> countrySecondCatCaseList = selectionService.getSecondCatScale(countryName,firstCatId,beginTime,endTime);
        /**
         * 求总和
         */
        double sum  = 0d;
        for(CountrySecondCatCase countrySecondCatCase:countrySecondCatCaseList){
            sum += countrySecondCatCase.getSaleRoom();
        }
        List<JSONObject> jsonObjects = new ArrayList<JSONObject>();
        for(CountrySecondCatCase countrySecondCatCase:countrySecondCatCaseList){
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("name",countrySecondCatCase.getSecondCatName());
            jsonObject1.put("data",String.format("%.2f", countrySecondCatCase.getSaleRoom()/sum));
            jsonObjects.add(jsonObject1);
        }
        /**
         * 设置返回对象
         */
        ResultBean resultBean = new ResultBean();
        resultBean.put("values",jsonObjects);
        resultBean.put("code",200);
        return resultBean;
    }

    /**
     * 根据二级类目获取top100店铺集中度
     * @param data
     * @return
     */
    @PostMapping("/getSecondCatShops")
    public ResultBean getSecondCatShops(@RequestBody String data){
        /**
         * 解析参数
         */
        JSONObject jsonObject = JSONObject.parseObject(data);
        Integer secondCatTitleId = jsonObject.getInteger("secondCatTitleId");
        String time = jsonObject.getString("time");
        try{
            List<SecondCatShopTopTen> secondCatShopTopTens = selectionService.getSecondCatShops(time,secondCatTitleId);
            /**
             * 获取销售金额总和
             */
            double sum = selectionService.getSecondCatShopsSaleRoom(time,secondCatTitleId);
            List<String> list = new ArrayList<String>();
            /**
             * 不丢失精度
             */
            BigDecimal bigDecimal = new BigDecimal("0");
            BigDecimal sumDecimal = new BigDecimal(String.valueOf(sum));
            for(int i=0;i<secondCatShopTopTens.size();i++){
                BigDecimal val = new BigDecimal(String.valueOf(secondCatShopTopTens.get(i).getSaleRoom()));
                bigDecimal = bigDecimal.add(val);
                if(i==0){
                    list.add(String.format("%.2f",secondCatShopTopTens.get(i).getSaleRoom()/sum*100));
                }else{
                    list.add(String.format("%.2f",bigDecimal.divide(sumDecimal,4,BigDecimal.ROUND_HALF_UP).doubleValue()*100));
                }
            }
            for(int i=0;i<list.size();i++){
                secondCatShopTopTens.get(i).setScale(Double.valueOf(list.get(i)));
            }
            return ResultBean.success("获取信息成功",secondCatShopTopTens);
        }catch (Exception e){
            e.printStackTrace();
            return ResultBean.error("获取信息失败");
        }
    }

    /**
     * 获取某个国家二级类目各个月份情况
     * @param data
     * @return
     */
    @PostMapping("/getSecondCatMonthScale")
    public ResultBean getSecondCatMonthScale(@RequestBody String data){
        /**
         * 解析参数
         */
        JSONObject jsonObject = JSONObject.parseObject(data);
        String countryName = jsonObject.getString("countryName");
        Integer firstCatId = jsonObject.getInteger("firstCatId");
        String beginTime = jsonObject.getString("beginTime");
        String endTime = jsonObject.getString("endTime");
        List<CountrySecondCatCase> countrySecondCatCaseList = selectionService.getSecondCatScale(countryName,firstCatId,beginTime,endTime);
        /**
         * 求总和
         */
        double sum  = 0d;
        for(CountrySecondCatCase countrySecondCatCase:countrySecondCatCaseList){
            sum += countrySecondCatCase.getSaleRoom();
        }
        List<JSONObject> jsonObjects = new ArrayList<JSONObject>();
        for(CountrySecondCatCase countrySecondCatCase:countrySecondCatCaseList){
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("name",countrySecondCatCase.getSecondCatName());
            jsonObject1.put("data",String.format("%.2f", countrySecondCatCase.getSaleRoom()/sum));
            jsonObjects.add(jsonObject1);
        }
        /**
         * 设置返回对象
         */
        ResultBean resultBean = new ResultBean();
        resultBean.put("values",jsonObjects);
        resultBean.put("code",200);
        return resultBean;
    }

    /**
     * 获取国家各个月份一级目录下二级目录的销售额    选品分析 5
     * @param data
     * @return
     */
    @PostMapping("/getSecondCatSaleRoom")
    public ResultBean getSecondCatSaleRoom(@RequestBody String data){
        /**
         * 解析参数
         */
        JSONObject jsonObject = JSONObject.parseObject(data);
        String countryName = jsonObject.getString("countryName");
        Integer firstCatId = jsonObject.getInteger("firstCatId");
        String beginTime = jsonObject.getString("beginTime");
        String endTime = jsonObject.getString("endTime");
        /**
         * 获取所有时间
         */
        List<String> times = selectionService.getAllTimeAsc(beginTime,endTime);
        /**
         * 格式化日期
         */
        List<String> timess = new ArrayList<>();
        for(String time:times){
            StringBuilder sb = new StringBuilder(time);
            sb.insert(4,"年");
            sb.append("月");
            timess.add(sb.toString());
        }
        /**
         * 所有名称
         */
        List<String> secondCatNames = selectionService.getSecondCatName(firstCatId,countryName);
        //存储返回内容
        List<JSONObject> jsonObjects = new ArrayList<JSONObject>();
        for(String secondCatName:secondCatNames){
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("name",secondCatName);
            jsonObject1.put("data",selectionService.getSecondCatSaleRoom(times,countryName,secondCatName));
            jsonObjects.add(jsonObject1);
        }
        /**
         * 设置返回对象
         */
        ResultBean resultBean = countryController.getTable(secondCatNames,jsonObjects,timess);
        resultBean.put("times",timess);
        resultBean.put("values",jsonObjects);
        resultBean.put("secondCatNames",secondCatNames);
        resultBean.put("code",200);
        return resultBean;
    }

    /**
     * 获取二级类目店铺排行榜 按视频展示结合国家top和某个行业的top交集求出 (选品分析  12)
     * @return
     */
    @PostMapping("/getSecondCatShopTop")
    public ResultBean getSecondCatShopTop(@RequestBody String data){
        /**
         * 解析参数
         */
        JSONObject jsonObject = JSONObject.parseObject(data);
        String countryName = jsonObject.getString("countryName");
        Integer secondCatTitleId = jsonObject.getInteger("secondCatTitleId");
        String time = jsonObject.getString("time");
        try{
            List<SecondCatShopTopTen> secondCatShopTopTens = selectionService.getSecondCatShopTop(time,countryName,secondCatTitleId);
            if(StringUtils.isEmpty(secondCatShopTopTens) || secondCatShopTopTens.size() == 0){
                return ResultBean.success("该国家下该类目无top店铺信息");
            }
            return ResultBean.success(secondCatShopTopTens);
        }catch (Exception e){
            logger.error(e.getMessage());
            return ResultBean.error("获取数据失败");
        }
    }

    /**
     * 获取某个月份二级类目top商品的价格分布  (选品分析  17)
     * @param data
     * @return
     */
    @PostMapping("/getSecondCatPriceRange")
    public ResultBean getSecondCatPriceRange(@RequestBody String data){
        JSONObject jsonObject = JSONObject.parseObject(data);
        Integer secondCatTitleId = jsonObject.getInteger("secondCatTitleId");
        String time = jsonObject.getString("time");
        //存储返回内容
        List<JSONObject> objectList = new ArrayList<JSONObject>();
        try{
            //获取所有商品
            List<SecondCatGoodsTopTen> list = selectionService.getAllGoodTop(time,secondCatTitleId);
            //计算价格区间步长
            double minPrice = list.get(0).getGoodsPrice();
            double maxPrice = list.get(list.size()-1).getGoodsPrice();
            double stepSize = Math.round(maxPrice/7d);
            //计算区间统计商品个数
            double j = minPrice;
            for(double i=minPrice+stepSize;i<=maxPrice+stepSize;i+=stepSize){
                double totalPrice = 0d;
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("name",String.format("%.2f",j) + "~" + String.format("%.2f",i));
                for(int m = 0; m < list.size(); m++){
                    double price = list.get(m).getGoodsPrice();
                    //因为升序排列，则可以直接跳出循环，方便遍历
                    if(price > i){
                        break;
                    }
                    if(j <= price && price <= i){ 
                        totalPrice += list.get(m).getSaleRoom();
                        list.remove(list.get(m));
                        m--;
                    }
                }
                jsonObject1.put("value",String.format("%.2f",(double)totalPrice/10000));
                //按照ppt去掉了为0的值
                if(!String.format("%.2f",(double)totalPrice/10000).equals("0.00")){
                    objectList.add(jsonObject1);
                }
                j = i;
            }
            return ResultBean.success(objectList);
        }catch (Exception e){
            return ResultBean.error("错误");
        }
    }


    /**
     * 获取某个月份二级类目top1国家top1-3物流及订单数量  (选品分析  21)
     * @param data
     * @return
     */
    @PostMapping("/getCountryTopThree")
    public ResultBean getCountryTopThree(@RequestBody String data){
        JSONObject jsonObject = JSONObject.parseObject(data);
        Integer secondCatTitleId = jsonObject.getInteger("secondCatTitleId");
        String time = jsonObject.getString("time");
        //返回第一国家名称
        String countryName = selectionService.getCountryName(time,secondCatTitleId);
        List<Map<String,Double>> map = selectionService.getTopThreeCount(time,secondCatTitleId,countryName);
        try{
            ResultBean resultBean = new ResultBean();
            resultBean.put("countryName",countryName);
            resultBean.put("data",map);
            resultBean.put("msg","获取数据成功");
            resultBean.put("code",200);
            return resultBean;
        }catch (Exception e){
            return ResultBean.error("错误");
        }
    }
}